﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class EditProduct : System.Web.UI.Page
{
    Product pd = new Product();
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if(this.IsPostBack==false)
        {
        ddlCatalog.DataSource = pd.GetCatalog();
        ddlCatalog.DataTextField = "CatalogName";
        ddlCatalog.DataValueField = "CatalogID";
        ddlCatalog.DataBind();
        ddlCategories.DataSource = pd.GetCategory();
        ddlCategories.DataTextField = "CategoriesName";
        ddlCategories.DataValueField = "CategoriesID";
        ddlCategories.DataBind();

        tblProduct pr;
        pr = pd.GetProductById(Session["PRID"].ToString());
        txtProductID.Text = pr.ProductID;
        txtPrice.Text = pr.Price.ToString();
        txtProductName.Text = pr.ProductName;
        txtShopDID.Text = pr.ShopDID;
        ddlCatalog.SelectedValue = pr.CatalogID;
        ddlCategories.SelectedValue = pr.CategoriesID;

        }
    }
    protected void btnSummit_Click(object sender, EventArgs e)
    {
        int cl =0;
        if(UploadImage.HasFile)
        {
            cl = 1;
        }
        if (pd.UpdateProduct(pd.getProductID(), txtShopDID.Text, ddlCategories.SelectedValue.ToString(), ddlCatalog.SelectedValue.ToString(), txtProductName.Text, float.Parse(txtPrice.Text.Trim()), upload(),cl))
        {
            txtProductID.Text = pd.getProductID();
            ddlCatalog.SelectedIndex = 0;
            ddlCategories.SelectedIndex = 0;
            txtShopDID.Text = null;
            txtProductName.Text = null;
            txtPrice.Text = null;
        }
    }
    string upload()
    {

        if (UploadImage.HasFile)
        {
            Random rb = new Random();
            int rand = rb.Next(1000);
            string name = rand.ToString() + "_" + UploadImage.PostedFile.FileName;
            try
            {
                UploadImage.SaveAs(Server.MapPath("~/images/Product/" + name));
                return name;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        else
        {
            return "no-picture.jpg";
        }

    }
}